/**
 * Looker  新闻整合系统
 * Author  :solosky
 * File    :Starter.java
 * Date    :May 13, 2009
 * Lisence : Apache License 2.0 
 */
package net.looker.starter;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

import net.looker.config.ConfigManager;
import net.looker.data.DataManager;
import net.looker.data.LuceneDataDriver;
import net.looker.data.MysqlDataDriver;
import net.looker.manager.MonitorManagerAgent;
import net.looker.monitor.schdule.MonitorManager;
import net.looker.work.WorkerPoolFactory;

import org.jdom.JDOMException;


/**
 * 初始化和启动整个Looker
 * @author solosky
 *
 */
public class Starter 
{
	private Logger logger;

	public Starter()
	{
		logger  = Logger.getLogger("looker");
	}
	
	/**
	 * 初始化数据管理器
	 */
	public void initDataManager()
	{
		DataManager.getInstance().addDataDriver(new MysqlDataDriver());
		DataManager.getInstance().addDataDriver(new LuceneDataDriver());
	}
	/**
	 * 加载配置 
	 * @param lookerConfigFile
	 * @throws JDOMException
	 * @throws IOException
	 */
	public void loadConfig(String lookerConfigFile) throws JDOMException, IOException
	{
		ConfigManager cm = ConfigManager.getInstance();
		//初始化栏目配置
		cm.loadLookerConfig(lookerConfigFile);
		//载入站点配置
		cm.loadSiteConfigs();
		//同步本地配置和数据库配置
		cm.SynchConfig();
		logger.info("成功加载配置");
	}
	
	/**
	 * 注册管理器
	 */
	public void registerMBean()
	{
		  MonitorManagerAgent mma = new MonitorManagerAgent(MonitorManager.getInstance());
		  MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		  try {
			server.registerMBean(mma, new ObjectName("looker:type=MonitorManagerAgent"));
			 logger.info("注册管理器成功。");
		} catch (InstanceAlreadyExistsException e) {
			e.printStackTrace();
		} catch (MBeanRegistrationException e) {
			e.printStackTrace();
		} catch (NotCompliantMBeanException e) {
			e.printStackTrace();
		} catch (MalformedObjectNameException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 初始化日志
	 * @throws SecurityException
	 * @throws IOException
	 */
	public void initLogger()
	{
		FileHandler fh = null;
		String savePath = ConfigManager.getInstance().getLookerConfig().get("looker.logSavePath");
		try {
			fh = new FileHandler(savePath);
		} catch (SecurityException e) {
			logger.severe("日志安全错误");
		} catch (IOException e) {
			logger.severe("日志文件读取错误");
		}
		fh.setFormatter(new SimpleFormatter());
		logger.addHandler(fh);
		Logger.getLogger("looker").info("成功初始化日志记录:"+savePath);
	}
	
	/**
	 * 建立线程池
	 */
	public void initWorkerPool()
	{
		WorkerPoolFactory.create("looker" , ConfigManager.getInstance().getCategoryCount()*2); //TODO ...
		logger.info("成功建立线程池:looker - " + ConfigManager.getInstance().getCategoryCount()*2);
		logger.info("等待所有线程启动完毕，请稍候....(等待5秒)");
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 初始化监视器
	 */
	public void initMonitor()
	{
		MonitorManager.getInstance().buildMonitor();
		logger.info("成功建立监视器");
	}
	
	/**
	 * 启动计划器
	 */
	public void startSchdule()
	{
		MonitorManager.getInstance().startSchedule();
		logger.info("成功启动计划器");
	}
	/**
	 * 主方法
	 * @param args
	 */
	
	public static void main(String[] args)
	{
		
		if(args.length==0){
			System.out.println("必须给定全局配置文件. 如 looker.xml");
			return ;
		}
		Logger logger  = Logger.getLogger("looker");
		Starter starter = new Starter();
		logger.info("Looker系统启动");
		try {
			starter.loadConfig(args[0]);
			//starter.loadConfig("./config/looker.xml");
		} catch (JDOMException e) {
			logger.severe("全局配置解析出错:程序将退出。");
			return;
		} catch (IOException e) {
			logger.severe("全局配置读取出错:程序将退出。");
			return;
		}
		//初始化日志记录器
		starter.initLogger();
		//建立线程池
		starter.initWorkerPool();
		//初始化监视器
		starter.initMonitor();
		//注册管理器
		starter.registerMBean();
		//启动计划器
		starter.startSchdule();
		
		logger.info("Looker启动完成");
		logger.info("looker正等待第一次检查新闻页面,请稍候....");
	}
}
